import React from 'react';
import { HashRouter as Router, Route, Redirect, Switch,withRouter } from 'react-router-dom'
import { asyncComponent } from 'react-async-component';
import {inject, observer} from 'mobx-react';
import { Browser, BrowserHrm, Upload, Reply } from 'weaver-mobile-page'
import { Tools, TextareaItem, Icon, Select, Accordion, List, InputItem, DatePicker, Modal, Toast, Button, Tabs, Popover, Tree, SwipeAction } from 'weaver-mobile';
import * as Util from "../../../util";
import * as GoalDetailAPI  from '../../../api/goal/goalDetail'
import * as GoalAddAPI from '../../../api/goal/goalAdd'
import WrAlertPage from '../../../public/alertPage'
import {toJS} from 'mobx';
const getLabel = Tools.getLabel;
@inject('goalSubInfoStore','goalCommonStore')
@withRouter
@observer
class GoalSubInfo extends React.Component {
    constructor(props){
        super(props);
        this.state = {}
    }

    componentWillMount() {
        const {goalId} = this.props;
        const { getSubGoalList,changeDatas } = this.props.goalSubInfoStore;
        getSubGoalList({goalId})

    }

    onFastAddSubGoal = (goalinfoDatas) => {
        const {goalId} = this.props;
        const { reply, datas, changeDatas,formatSubGoalToData } = this.props.goalSubInfoStore;
        let content = goalinfoDatas.text.replace(new RegExp(/<\/?[a-z]+>/img), "")
        reply.doClear()
        GoalAddAPI.addGoal({
            goalName: content,
            parentid: goalId,
        }).then(res => {
            if (res.status) {
                let newsubdatas = []
                res.subdatas.forEach((sub, i) => {
                    newsubdatas.push(formatSubGoalToData(sub, 1))
                })
                changeDatas([...datas, ...newsubdatas])
                // changeTaskDetail({ ...taskDetail, sublist: [...taskDetail.sublist, ...res.subdatas] })
            }
        })
    }


    onAddSubGoal = (nodeinfo) => {
        const parentId = nodeinfo._owner.key;
        let {datas} = this.props.goalSubInfoStore;
        let name = this.findNameByKey(parentId,toJS(datas));
        this.props.history.push("/goalHome/goalAdd?parentid=" + parentId+"&parentName="+name)
    }


    /**
     *递归查找名称
     */
    findNameByKey = (key,datas) => {
        let Deep;
        for(let i = 0;i < datas.length;i ++){
            if(key == datas[i].key){
               return datas[i].name.props.children;
            }else{
                if(datas[i].childs){
                  Deep = this.findNameByKey(key,toJS(datas[i].childs))
                  if(Deep){
                      return Deep;
                  }
                }
            }
        } 
    }


    render(){
        const {goalCommonStore,cancreate} =this.props;
        const { reply, datas, changeDatas,formatSubGoalToData,loading } = this.props.goalSubInfoStore;
        if(loading){
            goalCommonStore.showLoading()
        }else{
            goalCommonStore.closeLoading()
        }
          
        return (
            <div className="workrelate-mobile-subgoal-wrapper">
                <div className="content-wrapper">
                    {
                        datas.length > 0 ?
                            <Tree
                                async
                                onAsyncSelect={node => new Promise((resolve) => {
                                    const goalId = node.key;
                                    GoalDetailAPI.getSubGoalList({
                                        goalId
                                    }).then(res => {
                                        let childrenData = []
                                        res.subGoalList.forEach((sub, i) => {
                                            childrenData.push(formatSubGoalToData(sub, node.deep + 1))
                                        })
                                        resolve(childrenData)
                                    })
                                })}
                                datas={toJS(datas)}
                                rowKey="key"
                                checkable={0}
                                decorator={content => (
                                     <SwipeAction
                                        autoClose
                                        right={cancreate ? [
                                            {
                                                text: getLabel(508560,'新建下级目标'),
                                                onPress: () => this.onAddSubGoal(content),
                                                style: { backgroundColor: '#4D7AD8 ', color: 'white', fontFamily: "PingFang-SC-Medium", fontSize: "14@hd", padding: "0 10px" }
                                            } 
                                        ]:[]}
                                    >
                                        {content}
                                    </SwipeAction>
                                )}
                                // onExpanded={(...arg) => { console.log(arg) }}
                                onChange={data => changeDatas(data)}
                            />
                            :<WrAlertPage show={true} msg={getLabel(513865,'暂无下级')} icon={"no-data"} top="35%"/>
                        
                    }
                </div>
                {cancreate && <div className="bottom-wrapper">
                    <Reply.NoMask
                        wrappedComponentRef={ref => this.replyRef = ref} // 由于react升级，ref={ref => this.replyRef = ref} 这种方式不能用了，这里取ref请按照目前给的这个方式
                        store={reply}
                        showTabBar={false}
                        showOutInput={false}
                        showOutTabBar={false}
                        placeholder={getLabel(521726,'请输入子目标名称')}
                        onSubmit={datas => this.onFastAddSubGoal(toJS(datas))} // 提交的时候，如果需要清空数据，调用store的doClear方法
                        style={{"fontColor":"red"}}
                    />
                </div>}
            </div>
        )
    }

}
export default GoalSubInfo;